<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success">
      <el-step title="编辑课程信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>
    <el-form :model="courseInfo" :rules="rules" ref="ruleForm" label-width="120px">

      <el-form-item label="课程标题" prop="title">

        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 课程讲师 TODO -->

      <el-form-item label="选择讲师" prop="teacherId">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 所属分类 TODO -->
      <!--      二级联动-->
      <el-form-item label="选择课程分类" prop="subjectParentId">
        <!--        选中数据的绑定位置-->
        <el-select v-model="courseInfo.subjectParentId" @change="changeOne" placeholder="一级分类">
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id">
          </el-option>
        </el-select>
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="lessonNum" label="总课时">
        <el-input-number :min="1" :max="200000000" v-model="courseInfo.lessonNum" controls-position="right"
                         placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介 TODO -->
      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面 TODO -->

      <el-form-item label="课程封面" prop="cover">
        <el-upload
          class="avatar-uploader"
          :action="BASE_API+'/eduoss/fileoss'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="error"
          accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
          :before-upload="beforeAvatarUpload"
          :on-progress="progress">
          <img v-if="imageUrl" :src="imageUrl" alt="图片丢失了" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number :min="0" :max="200000000" v-model="courseInfo.price" controls-position="right" placeholder=""/>
        元
        <el-tag style="margin-left: 30px">免费课程请设置为0元</el-tag>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate('ruleForm')">保存并下一步</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>

  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  import { addCourse, getCourseById, editCourse } from '@/api/edu/course'
  import { getAllTeacherList } from '@/api/edu/teacher'
  import { getSubjectList } from '@/api/edu/subject'
  //导入富文本组件
  import Tinymce from '@/components/Tinymce'

  export default {
    // 富文本组件
    // 声明组件
    components: { Tinymce },
    data() {
      return {
        saveBtnDisabled: false,
        active: 0,
        // 对象
        courseInfo: {
          title: '',
          description: '',
          lessonNum: 0,
          price: 0.0,
          teacherId: '',
          //一级分类id
          subjectParentId: '',
          //二级分类id
          subjectId: '',
          //封面地址
          cover: ''
        },
        teacherList: [],
        //一级菜单
        subjectOneList: [],
        //二级菜单
        subjectTwoList: [],
        // 上传地址
        action: '',
        // 图片地址
        imageUrl: '',
        //BASE_API
        BASE_API: process.env.BASE_API,
        //表单校验
        rules: {
          title: [
            { required: true, message: '请填写课程标题', trigger: 'blur' },
            { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
          ],
          teacherId: [
            { required: true, message: '请选择所属讲师', trigger: 'change' }
          ],
          subjectParentId: [
            { required: true, message: '请选择课程分类', trigger: 'change' }
          ],
          cover: [
            { required: true, message: '请添加课程封面', trigger: 'change' }
          ]
        }

        //获取地址

      }
    },
    created() {
      this.getTeacherList()
      this.getSubjectList()
      if (this.$route.params && this.$route.params.id) {
        this.getCourse(this.$route.params.id)
      }
    },
    watch: {
      $route(from, to) {
        //此处富文本数据残留bug TODO
        this.courseInfo.description = ''
        this.getCourse(this.$route.params.id)
      }
    },
    methods: {
      //校验数据并提交
      saveOrUpdate(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //如果已存在id 则为修改 否则添加
            if (this.$route.params && this.$route.params.id) {
              this.editCourseInfo()
              //  修改
            } else {
              addCourse(this.courseInfo).then(response => {
                this.$message.success('添加成功!')
                //页面跳转
                this.$router.push({ path: '/edu/course/chapter/' + response.data.courseId })
              })
            }

          }
        })
      },
      //获取教师列表
      getTeacherList() {
        getAllTeacherList().then(response => {
          this.teacherList = response.data.items
        })
      },
      //获取整个分类菜单
      getSubjectList() {
        getSubjectList().then(response => {
          // console.log(response.data.data2[0])
          this.subjectOneList = response.data.data2

        }).catch(error => {

        })
      },
      // 选中时筛选填充二级菜单
      changeOne(value) {
        // this.subjectTwoList = [],
        for (let i = 0; i < this.subjectOneList.length; i++) {
          //选中id等于一级菜单中的id
          if (this.subjectOneList[i].id == value) {
            this.subjectTwoList = this.subjectOneList[i].children
            // 设置二级菜单默认选中项
            this.courseInfo.subjectId = this.subjectTwoList[0].id
          }
        }
      },
      //上传成功之后
      handleAvatarSuccess(res, file) {
        // res 为上传成功的对象
        //   console.log("res:"+res.data.url)
        //   console.log("file:"+file.data)
        // 将图片路径填充至对象路径
        this.$notify({
          title: '成功',
          message: '图片成功!',
          type: 'success'
        })
        this.courseInfo.cover = res.data.url
        this.imageUrl = URL.createObjectURL(file.raw)
        // this.imageUrl = res.data.url
        // console.log(this.imageUrl)
      },
      //上传之前的检测
      beforeAvatarUpload(file) {
        let isImg = file.name
        isImg = isImg.toLowerCase()
        if (isImg.endsWith('.gif') || isImg.endsWith('.png') || isImg.endsWith('.svg') || isImg.endsWith('.jpg') || isImg.endsWith('.jpeg')) {
          isImg = true
        } else {
          isImg = false
        }
        //文件大小 默认以byte为单位
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isImg) {
          this.$message.error('上传图片只能是 gif/png/svg/jpg/jpeg格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isImg && isLt2M
      },
      // 上传中调用的方法
      progress() {
        this.$notify({
          title: '上传中',
          message: '图片上传中...',
          type: 'info'
        })
      },
      error() {
        this.$notify({
          title: '失败',
          message: '图片上传失败!',
          type: 'error'
        })
      },
      //根据id查询Course 做数据回显
      getCourse(courseId) {
        getCourseById(courseId).then(response => {
          this.courseInfo = response.data.courseInfoVo
          this.imageUrl = this.courseInfo.cover
          // 重新排列二级菜单 并选中
          this.getSubjectList()
          for (let i = 0; i < this.subjectOneList.length; i++) {
            if (this.subjectOneList[i].id == response.data.courseInfoVo.subjectParentId) {
              this.subjectTwoList = this.subjectOneList[i].children
            }
          }
        })
      },
      editCourseInfo() {
        editCourse(this.courseInfo).then(response => {
          this.$message.success(response.message)
          this.$router.push({ path: '/edu/course/chapter/' + this.$route.params.id })
        })
      }

    }

    //

  }
</script>

<style>
  .tinymce-container {
    line-height: 29px;
    width: 80%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 300px;
    line-height: 300px;
    text-align: center;
  }

  .avatar {
    width: 300px;
    height: 300px;
    display: block;
  }
</style>
